#!/bin/bash
# ****************************************************
#   dg_start_db.sh
#   Written by McDull Zeng 2012-10-28   
#   
#   This script is used to startup Oracle 11gR2 in a Active Data Guard cluser.
#   It does determines the database role, and 
#       1. open the PRIMARY db
#       or
#       2. open STANDBY db read only and realtime apply redo logs
#
#   Usage: just add item in /etc/init.d/rc.local ==> su – oracle -c "/home/oracle/script/dg_start_db.sh"
# ****************************************************

# User specific environment and startup programs
if [ -f ~/.bash_profile ];
then
  . ~/.bash_profile
fi

# startup listener
lsnrctl start

# determine the database role (Primary/Standby)
sqlplus -s / as sysdba <<EOF
    spool /tmp/oracle_role.log
    startup mount;
    set pages 0
    set head off
    set feed off
    select database_role from v\$database;
    spool off
    exit;
EOF

DB_ROLE=`cat /tmp/oracle_role.log | tail -1`
#echo "ROLE = ${DB_ROLE}"

if [ `echo $DB_ROLE | grep 'PRIMARY' | wc -l` -eq 1 ];then
    sqlplus -s / as sysdba <<EOF
        alter database open;
        exit;
EOF
elif [ `echo $DB_ROLE | grep 'PHYSICAL STANDBY' | wc -l` -eq 1 ];then
    sqlplus -s / as sysdba <<EOF
        alter database open read only;
        alter database recover managed standby database disconnect from session using current logfile;
        exit;
EOF
fi

